<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\AuthRole;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Entity\AuthLinkRolePermissions;
use AdminBundle\Utility\Constant;

/**
 * Authrole controller.
 *
 * @Route("authrole")
 */
class AuthRoleController extends BaseController
{
    /**
     * Lists all authRole entities.
     *
     * @Route("/", name="authrole_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $starttime = $request->get('starttime');
        $endtime = $request->get('endtime');

        $starttime = $starttime ? $starttime : date("Y-m-d", strtotime("-1 day"));
        $endtime = $endtime ? $endtime : date("Y-m-d", strtotime("+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime];

        $result = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->pageQuery($params, $page);

        return $this->render('AdminBundle:authrole:index.html.twig', array_merge([
            'authRoles' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new authRole entity.
     *
     * @Route("/new", name="authrole_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $authRole = new Authrole();
        $form = $this->createForm('AdminBundle\Form\AuthRoleType', $authRole, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $authRole->setCtime(new \DateTime());
            $authRole->setCreateUser($this->getUser()->getUsername());
            $em = $this->getDoctrine()->getManager();
            $em->persist($authRole);
            $em->flush();

            $this->assignPermission($request, $authRole);

            return $this->redirectToRoute('authrole_show', array('id' => $authRole->getId()));
        }
        $authPermissions = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->loadRolePermissions();

        return $this->render('AdminBundle:authrole:new.html.twig', array(
            'authRole' => $authRole,
            'form' => $form->createView(),
            'authPermissions' => $authPermissions
        ));
    }

    public function assignPermission(Request $request, Authrole $authRole)
    {
        $permissions = [];
        // 设置角色的权限
        $auth_role = $request->request->get('auth_role', []);
        if (isset($auth_role['permission']) && !empty($auth_role['permission'])) {
            $em = $this->getDoctrine()->getManager();

            $permissions = $auth_role['permission'];
            foreach ($permissions as $permission) {
                // 滤重
                $obj_is_exists = $em->getRepository('AdminBundle:AuthRole')->loadByRoleIdAndPermissionId(
                    $authRole->getId(), trim($permission)
                );
                if ($obj_is_exists != null)
                    continue;
                // 权限
                $authPermission = $em->getRepository('AdminBundle:AuthPermission')->findOneBy(['id' => $permission]);

                $authLinkRolePermission = new AuthLinkRolePermissions();
                $authLinkRolePermission->setCreateUser($this->getUser()->getUsername())
                    ->setCtime(new \DateTime())
                    ->setRole($authRole)
                    ->setPermission($authPermission);
                $em->persist($authLinkRolePermission);
            }
            $em->flush();
        }
        return $permissions;
    }

    /**
     * Finds and displays a authRole entity.
     *
     * @Route("/{id}", name="authrole_show")
     * @Method("GET")
     */
    public function showAction(AuthRole $authRole)
    {
        $deleteForm = $this->createDeleteForm($authRole);

        return $this->render('AdminBundle:authrole:show.html.twig', array(
            'dataSource' => $authRole,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing authRole entity.
     *
     * @Route("/{id}/edit", name="authrole_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, AuthRole $authRole)
    {
        $deleteForm = $this->createDeleteForm($authRole);
        $editForm = $this->createForm('AdminBundle\Form\AuthRoleType', $authRole, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            $permissionIds = $this->assignPermission($request, $authRole);

            $ret = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->revokeRolePermission($authRole->getId(), $permissionIds);

            return $this->redirectToRoute('authrole_edit', array('id' => $authRole->getId()));
        }
        $authPermissions = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->loadRolePermissions($authRole->getId());

        return $this->render('AdminBundle:authrole:edit.html.twig', array(
            'dataSource' => $authRole,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'authPermissions' => $authPermissions
        ));
    }

    /**
     * Deletes a authRole entity.
     *
     * @Route("/{id}", name="authrole_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, AuthRole $authRole)
    {
        $form = $this->createDeleteForm($authRole);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($authRole);
            $em->flush();
        }

        return $this->redirectToRoute('authrole_index');
    }

    /**
     * Creates a form to delete a authRole entity.
     *
     * @param AuthRole $authRole The authRole entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(AuthRole $authRole)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('authrole_delete', array('id' => $authRole->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
